package com.ericsson.common.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ScpUtil {

    private Connection connection;

    private SCPClient scpClient;

    public ScpUtil(String ip, String user, String password) throws IOException {

        connection = new Connection(ip, 22);
        connection.connect();
        boolean b = isAuthedWithPassword(user, password);
        if (b) {
            scpClient = connection.createSCPClient();
        }
    }

    public void getFile(String remoteFile,String name, String path) throws IOException {
        File newFile = new File(path+File.separator+name);
        FileOutputStream fos = new FileOutputStream(newFile);
        mkdirs(path);
        SCPInputStream sis = scpClient.get(remoteFile);
        byte[] b = new byte[4096];
        int i;
        while ((i = sis.read(b)) != -1){
            fos.write(b,0, i);
        }
        fos.flush();
        fos.close();
        sis.close();
    }
    /**
     * 如果目录不存在就创建目录 *
     *
     * @param path
     */
    public void mkdirs(String path) {
        File f = new File(path);
        if (!f.exists()) {
            System.out.println("mkdir :" + path);
            f.mkdirs();
        }
    }


    public boolean isAuthedWithPassword(String user, String password) {
        try {
            return connection.authenticateWithPassword(user, password);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void disconnect() {
        connection.close();
    }

    public static void main(String args[]) throws Exception{
        ScpUtil scp;
        scp = new ScpUtil("10.239.69.64", "epc_expert", "1hblsqT#");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        System.out.println(date);
        System.out.println(System.currentTimeMillis());
        scp.getFile("/logs/ebs/ready" + "/" + "A20210201.1030+0800-20210201.1045+0800_30_ebs.160","A20210201.1030+0800-20210201.1045+0800_30_ebs.160", "/opt");
        System.out.println(System.currentTimeMillis());
        String date2 = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        System.out.println(date2);

        scp.disconnect();
    }

}
